<template>
  <Modal
    v-model:visible="visible"
    :title="getTitle"
    :confirm-loading="confirmLoading"
    @ok="handleSubmit"
    @cancel="closeModal"
    okText="确认"
    cancelText="取消"
  >
    <BasicForm @register="registerForm" />
  </Modal>
</template>

<script lang="ts" setup>
import { Modal } from 'ant-design-vue';
import BasicForm from '/@/components/BasicForm/BasicForm.vue';
import { useBasicForm } from '/@/components/BasicForm/hooks/useBasicForm';
import { computed, nextTick, ref, unref } from 'vue';
import { addOrUpdateSfs } from '/@/api/system-mgmt/sfs-mgmt/sfs';
import { fileSystemSizeSchema } from '/@/views/system-mgmt/fileSystemSize-mgmt/data';

const visible = ref<boolean>(false);
const isUpdate = ref(true);
const confirmLoading = ref<boolean>(false);
const getTitle = computed(() => (!unref(isUpdate) ? '创建文件系统规格' : '编辑文件系统规格'));
const id = ref();
const emit = defineEmits(['success', 'register']);

const [registerForm, { resetFields, setFieldsValue, validate }] = useBasicForm({
  labelWidth: 100,
  schemas: fileSystemSizeSchema,
  showActionButtonGroup: false,
});

const showModal = async (record: Recordable, update: boolean) => {
  visible.value = true;
  isUpdate.value = update;
  await resetFields();
  if (update === true)
    nextTick(async () => {
      id.value = record.id;
      await setFieldsValue(record);
    });
};

const closeModal = () => {
  visible.value = false;
};

async function handleSubmit() {
  try {
    const values = await validate();
    if (isUpdate.value === true) {
      values.id = id.value;
    }
    await addOrUpdateSfs(values);
    closeModal();
    emit('success');
  } finally {
    confirmLoading.value = false;
  }
}

defineExpose({ showModal });
</script>